#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
//复制控制的第二版：
//派生类中定义自己的数据成员，但是此时依然不去显示定义复制控制函数
class Base{
public:
    Base(const char * pstr)
    :_base(new char[strlen(pstr) + 1]())
    {
        strcpy(_base, pstr);
    }

    Base(const Base & rhs)
    :_base(new char[strlen(rhs._base) + 1]())
    {
        strcpy(_base, rhs._base);
    }
    //赋值运算符
    Base & operator=(const Base & rhs){
        if(this != &rhs){
            delete [] _base;
            _base = new char[strlen(rhs._base) + 1]();
            strcpy(_base, rhs._base);
        }
        return *this;
    }
    ~Base(){
        if(_base){
            delete [] _base;
            _base = nullptr;
        }
    }

protected:
    char * _base;
};
//派生类中定义一个char *数据成员，使用的是深拷贝
class Derived : public Base{
public:
    //第二版中我们的做法是派生类新增一个指针数据成员，主动申请堆空间
    //于此同时提供构造函数和析构函数，但是并没有主动去提供
    //拷贝构造函数和赋值运算符函数
    //出现double free的情况
    //三合成原则
    Derived(const char * base, const char * derived)
    :Base(base)
    ,_derived(new char[strlen(derived) + 1]())
    {
        strcpy(_derived, derived);
        cout << "Derived(const char *)" << endl;
    }
    friend ostream & operator<<(ostream & os, const Derived & rhs);

    ~Derived(){
        if(_derived){
            delete [] _derived;
            _derived = nullptr;
        }
    }

private:
    char * _derived;
};
ostream & operator<<(ostream & os, const Derived & rhs){
    os << rhs._base;
    return os;
}


void test(){
    Derived d1("hello", "world");
    Derived d2 = d1;
}

int main()
{
    test();
    return 0;
}

